var wxParse = require('../../wxParse/wxParse.js');
var common = require("../../utils/Conmon.js");
var app = getApp();
var apiurl = app.globalData.apiurl;
var imgurl = app.globalData.imgurl;
var selectIndex = []
var num = 1;
var Status = 0;
var PageIndex = 1;
var PageSize = 5;
var IsLastPage = false;
var isSatisfy = true; //是否满足购买
var goodsinfoList = [];
var goodsinfo = null;
var result = null;
Page({
  data: {
    array: ['参数1', '参数2'],
    cansu: false,
    index: 0,
    like: false,
    tab: [{
        id: "0",
        text: "商品详情",
        selected: true
      },
      {
        id: "1",
        text: "商品评价",
        selected: false
      },
    ],
    imgUrls: [],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 500,
    popin: false,
    sharepopin: false,
    selected: true,
    selected1: false,
    nocomment: true,
    productId: 0,
    vo: [],
    specList: [],
    num: num,
    _spechtml: "",
    goodsinfo: null,
    shopID: 0,
    CommentList: [],
    storeHide: true,
    shopName: "",
    Logo: "",
    StockNum: 0,
    SurplusStockNum: 0,
    CollectionNum: 0,
    activityDetails: 'display: none',
    noActivityDetails: 'display: block',
    activityOverDay: "00",
    activityOverHour: "00",
    activityOverMinute: "00",
    activityOverSecond: "00",
    Activitys: [],
    LimitBuyNum: 0, //限购数量
    IsLimitBuy: false, //是否限购
    HasBuyNum: 0 //目前已经买了多少件
  },
  onShareAppMessage(res) {
    var that = this;
    var pic = this.data.vo.ProductInfo.ProductImg;
    var ptitle = this.data.vo.ProductInfo.ProductName;
    var price = this.data.vo.ProductInfo.CurrentPrice;
    var url = '/pages/details/details?productId=' + this.data.productId + '&shopID=' + this.data.shopID;
    return {
      title: ptitle,
      imageUrl: pic,
      path: url,
      success: function(res) {
        var data = {
          CustID: app.globalData.custID,
          UserID: wx.getStorageSync('UserInfo').UserID,
          ProductID: that.data.productId,
          Name: ptitle,
          Img: pic,
          Price: price,
          Commission: 0,
          Link: url
        };
        wx.request({
          url: app.globalData.apiurl + "/mobile/api/ShareLog/Log",
          data: JSON.stringify(data),
          method: 'POST',
          header: {
            'X_ManuName': app.globalData.manuName,
            "test": "213123"
          },
          success: function(res) {

          }
        })
      },
      fail: function(res) {
        // 转发失败
      }
    }
  },
  //加载数据
  loadDetail: function() {
    var that = this;
    wx.showLoading({
      title: '加载中...',
      mask: true
    });


    wx.request({
      url: app.globalData.apiurl + '/mobile/api/Product/GetProductDetail',
      data: {
        custId: app.globalData.custID,
        productId: that.data.productId,
        userId: wx.getStorageSync('UserInfo').UserID,
        unionShopID: that.data.shopID
      },
      method: 'GET',
      header: {
        'X_ManuName': app.globalData.manuName,
        "test": "213123"
      },
      success: function(res) {
        wx.hideLoading();

        if (res.data.code == 1200) {

          result = res.data.content;
          goodsinfoList = result.GoodsInfoList;
          isSatisfy = result.IsSatisfy;
          selectIndex = [];
          goodsinfo = null;
          var like = false;
          if (result.Like) {
            like = true;
          } 
          if (result.ActivityType == 1 ) {
            that.setData({
              LimitBuyNum: result.LimitBuyNum,
              IsLimitBuy: result.IsLimitBuy,
              HasBuyNum: result.HasBuyNum
            });

          }

          that.setData({
            BuyAndGiftLimit: result.BuyAndGiftLimit,
            BuyAndGiftHasBuy: result.BuyAndGiftHasBuy
           
          });

          if (result.ProductDetail.Detail) {
            wxParse.wxParse('content', 'html', result.ProductDetail.Detail, that, 5)
          }
          if (result.ProductDetail.Parameter) {
            wxParse.wxParse('content2', 'html', result.ProductDetail.Parameter, that, 5)
          }

          var specList = null;
          //选中操作
          if (result != null && result.GoodsInfoList != null && result.GoodsInfoList.length > 0) {
            var goodsInfoList = result.GoodsInfoList;
            specList = result.SpecList;
            var miniPrice = result.ProductInfo.CurrentPrice;
            if (goodsInfoList != num && goodsInfoList.length > 0) {
              miniPrice = goodsInfoList[0].CurrentPrice;
              for (var i = 0; i < goodsInfoList.length; i++) {
                if (goodsInfoList[i].CurrentPrice < miniPrice) {
                  miniPrice = goodsInfoList[i].CurrentPrice;
                }
              }
            }

            for (var i = 0; i < goodsInfoList.length; i++) {
              if (goodsInfoList[i].CurrentPrice == miniPrice) {
                if (goodsInfoList[i].IsLimitBuy && result.ActivityType == 3) {
                  that.setData({
                    LimitBuyNum: goodsInfoList[i].LimitBuyNum,
                    IsLimitBuy: goodsInfoList[i].IsLimitBuy,
                    HasBuyNum: goodsInfoList[i].HasBuyNum
                  });

                }
                var specStrs = goodsInfoList[i].SpecID.split(",");
                if (specStrs != null && specStrs.length > 0) {
                  if (specList.length > 0) {
                    for (var j = 0; j < specList[0].length; j++) {

                      if (specList[0][j].ID == parseInt(specStrs[0])) {
                        specList[0][j].IsChecked = true;
                        that.changeSpec(specList[0][j].ID, specList[0][j].ParentID, specList);
                        break;
                      }
                    }
                  }

                  if (specList.length > 1) {
                    for (var j = 0; j < specList[1].length; j++) {

                      if (specList[1][j].ID == parseInt(specStrs[0])) {
                        specList[1][j].IsChecked = true;
                        that.changeSpec(specList[1][j].ID, specList[1][j].ParentID, specList);
                        break;
                      }
                    }
                  }
                }


                if (specStrs != null && specStrs.length >= 2) {
                  if (specList.length > 1) {
                    for (var j = 0; j < specList[1].length; j++) {
                      if (specList[1][j].ID == parseInt(specStrs[1])) {
                        specList[1][j].IsChecked = true;
                        that.changeSpec(specList[1][j].ID, specList[1][j].ParentID, specList);
                        break;
                      }
                    }
                  }

                  if (specList.length > 0) {
                    for (var j = 0; j < specList[0].length; j++) {
                      if (specList[0][j].ID == parseInt(specStrs[1])) {
                        specList[0][j].IsChecked = true;
                        that.changeSpec(specList[0][j].ID, specList[0][j].ParentID, specList);
                        break;
                      }
                    }
                  }

                }
                break;
              }

            }
          }
          //限时优惠
          if (result.ActivityType == 3) {
            that.setData({
              activityDetails: 'display: block',
              noActivityDetails: 'display: none'
            });
          } else {
            that.setData({
              activityDetails: 'display: none',
              noActivityDetails: 'display: block'
            });
          }
          //活动结束时间倒计时
          var RTime = setInterval(function() {
            var str = getRTime(result.EndDt);
            if (str != "") {
              var arr = str.split(',');
              that.setData({
                activityOverDay: arr[0],
                activityOverHour: arr[1],
                activityOverMinute: arr[2],
                activityOverSecond: arr[3],
              });
            } else {
              clearInterval(RTime);
              that.setData({
                activityOverDay: "00",
                activityOverHour: "00",
                activityOverMinute: "00",
                activityOverSecond: "00",
              });
            }
          }, 1000);

          that.setData({
            vo: result,
            specList: specList,
            imgUrls: result.ProductInfo.ProductImgList,
            like: like,
            Activitys: result.Activitys
          });
        }
      }
    })

    QueryCommentList(this);
  },

  bindPickerChange: function(e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  //收藏
  changlike: function() {
    collect(this);
  },
  changetab: function(e) {
    var id = e.currentTarget.id;
    var tab = this.data.tab;
    var len = tab.length;
    for (var i = 0; i < len; i++) {
      if (tab[i].id == id) {
        if (id == 1 && PageIndex == 1) {

        }
        tab[i].selected = true;
      } else {
        tab[i].selected = false;
      }
    }
    this.setData({
      tab: tab
    });
  },
  cansuPop: function() {
    this.setData({
      cansu: !this.data.cansu
    });
  },
  sharePop: function() {
    this.setData({
      sharepopin: !this.data.sharepopin
    });
  },
  selectGg: function(e) {
    this.setData({
      popin: !this.data.popin
    });
  },
  onLoad: function(options) {
    num = 1;
    Status = 0;
    PageIndex = 1;
    PageSize = 5;
    IsLastPage = false;
    isSatisfy = true;

    common.pageInit(function() {});
    var shopID = 0;
    var storeHide = true;
    if (options.shopID > 0) {
      shopID = options.shopID;
      storeHide = false;
    }
    this.setData({
      productId: options.productId,
      shopID: shopID,
      storeHide: storeHide
    });

    this.loadDetail(this);
    if (shopID > 0) {
      loadUnionStore(this);
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (this.data.tab[1].selected) {
      if (IsLastPage) {
        wx.showToast({
          title: '已到底',
          icon: 'loading',
          duration: 2000
        })
        return false;
      }
      ++PageIndex;
      QueryCommentList(this);
    }
  },

  //减少数量
  onsub: function(e) {
    num--;
    if (num < 1) {
      num = 1;
    }
    this.setData({
      num: num
    })
  },
  //增加数量
  onplus: function(e) {

    var resBuy = this.data.LimitBuyNum - this.data.HasBuyNum;
    if (resBuy < 0) {
      resBuy = 0;
    }
    //活动限购数
    if (this.data.IsLimitBuy == true && parseInt(num) >= resBuy) {

      var msg = "每人限购" + this.data.LimitBuyNum + "件";
      wx.showToast({
        title: msg,
        icon: 'none',
        duration: 2000
      })
      return;
    }
    num++;
    this.setData({
      num: num
    })
  },
  onblur: function(e) {
    num = e.detail.value;

    var r = /^\+?[1-9][0-9]*$/;　　 //正整数  
    var flag = r.test(num);
    if (isNaN(num) || !flag || num < 1) {
      num = 1;
    }

    var resBuy = this.data.LimitBuyNum - this.data.HasBuyNum;
    if (resBuy < 0) {
      resBuy = 0;
    }
    //活动限购数
    if (this.data.IsLimitBuy == true && parseInt(num) > resBuy) {

      var msg = "每人限购" + this.data.LimitBuyNum + "件";
      wx.showToast({
        title: msg,
        icon: 'none',
        duration: 2000
      })
      num = 1;
    }

    this.setData({
      num: num
    })
  },
  //选择规格
  onselectspec: function(e) {
    var that = this;
    var id = e.currentTarget.id;
    var pid = e.currentTarget.dataset.pid;
    var list = that.data.specList;
    that.changeSpec(id, pid, list);

  },
  changeSpec: function(id, pid, list) {
    var that = this;

    selectIndex[pid] = id

    var arr = [];
    for (var i = 0, len = selectIndex.length; i < len; ++i) {
      if (selectIndex[i])
        arr.push(selectIndex[i]);
    }
    var _specIds = arr.sort().join(',');
    for (var i = 0, len = goodsinfoList.length; i < len; ++i) {
      if (goodsinfoList[i].SpecID == _specIds) {
        goodsinfo = goodsinfoList[i];
      }
    }

    var _specArr = [];
    for (var i = 0, len = list.length; i < len; ++i) {
      for (var j = 0, length = list[i].length; j < length; ++j) {
        if (list[i][j].ParentID == pid && list[i][j].ID != id) {
          list[i][j].IsChecked = false;
        }
        if (list[i][j].ID == id) {
          list[i][j].IsChecked = true;
        }
        for (var k = 0, len2 = arr.length; k < len2; ++k) {
          if (arr[k] == list[i][j].ID) {
            _specArr.push(list[i][j].SpecValue);
          }
        }
      }
    }
    that.setData({
      specList: list,
      _spechtml: _specArr.join('-'),
      goodsinfo: goodsinfo
    })
  },
  //加入购物车
  addtocart: function(e) {
    if (!isSatisfy) {
      wx.showModal({
        content: "会员等级不能购买此活动产品",
        showCancel: false,
        confirmText: "确定"
      })
      return;
    }
    var hasSpec = goodsinfoList != undefined && goodsinfoList != null && goodsinfoList.length > 0;
    var productId = result.ProductInfo.ProductID;
    var goodsId = 0;
    var canBuyStock = result.ProductDetail.StockNum;
    //有规格的商品
    if (hasSpec) {
      if (goodsinfo != null) {
        productId = goodsinfo.ProductID;
        goodsId = goodsinfo.GoodsID;
        canBuyStock = goodsinfo.StockNum;
      } else {
        wx.showModal({
          content: "请选择规格",
          showCancel: false,
          confirmText: "确定"
        })
        return;
      }
    }

    if ((!goodsinfo || goodsinfo == undefined) && hasSpec) {
      wx.showModal({
        content: "请选择规格",
        showCancel: false,
        confirmText: "确定"
      })
      return;
    }

    if (num <= 0 || num > canBuyStock) {
      wx.showModal({
        content: "库存不足",
        showCancel: false,
        confirmText: "确定"
      })
      return;
    }

    var LimitBuyNum = this.data.LimitBuyNum;
    var HasBuyNum = this.data.HasBuyNum;
    var IsLimitBuy = this.data.IsLimitBuy;
    var BuyAndGiftLimit = this.data.BuyAndGiftLimit;
    var  BuyAndGiftHasBuy= this.data.BuyAndGiftHasBuy;
    var resBuy = LimitBuyNum - HasBuyNum;
    if (resBuy < 0) {
      resBuy = 0;
    }

    //活动限购数
    if (num <= 0 || (IsLimitBuy == true && parseInt(num) > resBuy)) {

      var msg = "每人限购" + LimitBuyNum + "件";
      wx.showToast({
        title: msg,
        icon: 'none',
        duration: 2000
      });
      return;
    }
    //买满送限购数
    if (BuyAndGiftLimit>0 && BuyAndGiftHasBuy >= BuyAndGiftLimit) {

      var msg = "每人限购" + BuyAndGiftLimit + "次";
      wx.showToast({
        title: msg,
        icon: 'none',
        duration: 2000
      });
      return;
    }
    var data = {
      ProductID: productId,
      BuyNum: num,
      GoodsID: goodsId,
      CustID: app.globalData.custID,
      UserID: wx.getStorageSync('UserInfo').UserID,
      ShopId: this.data.shopID
    };
    var that = this;
    var typeid = e.currentTarget.dataset.type;
    var url = app.globalData.apiurl + "/mobile/api/ShopCart/InsertShopCart";
    if (typeid == 1) { //立即购买
      url = app.globalData.apiurl + '/mobile/api/ShopCart/BuyNow';
    }
    wx.request({
      url: url,
      data: JSON.stringify(data),
      method: 'POST',
      header: {
        'X_ManuName': app.globalData.manuName,
        "test": "213123"
      },
      success: function(res) {
        if (res.data.code == 1200) {
          if (typeid == 1) { //立即购买
            var cart = res.data.content;
            if (cart) {
              var clist = [];
              clist.push(cart);
              //将购物车选中项缓存起来
              wx.setStorageSync('Winmobi4MallSelectedShopCart', clist);
              wx.navigateTo({
                url: '/pages/submitOrder/submitOrder'
              })
            } else {
              wx.showModal({
                content: '操作失败',
                showCancel: false,
                confirmText: "确定"
              })
            }
          } else {
            that.setData({
              popin: false
            });
            wx.showToast({
              title: '操作成功',
              icon: 'success',
              duration: 2000
            })
          }
        } else {
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            confirmText: "确定"
          })
        }
      }
    })
  },
  //购物车
  gocart: function(e) {
    wx.switchTab({
      url: '/pages/cart/cart'
    })
  }
})


//收藏
function collect(that) {
  var data = {
    CustID: app.globalData.custID,
    UserID: wx.getStorageSync('UserInfo').UserID,
    ProductID: that.data.productId,
    UnionShopID: that.data.shopID
  };
  var collectUrl = "";
  if (that.data.like) {
    collectUrl = app.globalData.apiurl + "/mobile/api/Collection/CancelCollection";
  } else {
    collectUrl = app.globalData.apiurl + "/mobile/api/Collection/InsertMemberCollection";
  }
  wx.request({
    url: collectUrl,
    data: JSON.stringify(data),
    method: 'POST',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function(res) {
      if (res.data.code == 1200) {
        that.setData({
          like: !that.data.like
        });
        wx.showToast({
          title: res.data.content,
          icon: 'success',
          duration: 2000
        })
      } else {
        console.log(res.data.msg);
      }
    }
  })
}

//获取商品评价列表
function QueryCommentList(obj) {


  var url = apiurl + '/mobile/api/Product/GetCommentList';

  wx.request({
    url: url,
    data: {
      "CustId": app.globalData.custID,
      "Id": obj.data.productId,
      "Status": Status,
      "PageIndex": PageIndex,
      "PageSize": PageSize,
      "IsMyComment": 1,
      UnionStoreID: obj.data.shopID
    },
    method: 'GET',
    header: {
      'content-type': 'application/json',
      'X_ManuName': app.globalData.manuName
    },
    success: function(res) {

      if (res.data.content == null) {
        obj.setData({
          nocomment: false
        })
        return false;
      }
      var dlist = obj.data.CommentList;
      var d = res.data.content.Data;
      for (var i = 0; i < d.length; i++) {
        dlist.push(d[i]);
      }
      obj.setData({
        CommentList: dlist
      })
      if (d.length != PageSize) {
        IsLastPage = true;
        return false;
      }
    },
    fail: function() {

      wx.showToast({
        title: '获取评论列表失败',
        duration: 2000
      })
    },
    complete: function() {
      //complete
    }
  })
}

function loadUnionStore(that) {
  wx.request({
    url: app.globalData.apiurl + '/mobile/api/Unionstore/GetShopByID',
    data: {
      CustId: app.globalData.custID,
      UnionShopID: that.data.shopID
    },
    method: 'GET',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function(res) {

      if (res.data.code == 1200) {
        var result = res.data.content;
        that.setData({
          shopName: result.ShopName,
          imgUrls: app.globalData.imgurl + result.Logo
        });
      }
    }
  });

  wx.request({
    url: app.globalData.apiurl + '/mobile/api/Product/SumUnionStoreStock',
    data: {
      CustId: app.globalData.custID,
      UnionStoreID: that.data.shopID
    },
    method: 'GET',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function(res) {

      if (res.data.code == 1200) {
        var result = res.data.content;
        that.setData({
          StockNum: result.StockNum,
          SurplusStockNum: result.SurplusStockNum
        });
      }
    }
  });

  wx.request({
    url: app.globalData.apiurl + '/mobile/api/Product/CountUnionShopCollection',
    data: {
      CustId: app.globalData.custID,
      UnionStoreID: that.data.shopID
    },
    method: 'GET',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function(res) {

      if (res.data.code == 1200) {
        var result = res.data.content;
        that.setData({
          CollectionNum: result

        });
      }
    }
  });

}
//天时分秒
function getRTime(time) {
  var EndTime = newDate(time); //截止时间
  var NowTime = new Date();

  var t = EndTime.getTime() - NowTime.getTime();
  if (t > 0) {
    var d = Math.floor(t / 1000 / 60 / 60 / 24);
    var h = Math.floor(t % (24 * 3600 * 1000) / 1000 / 60 / 60);
    var m = Math.floor(t / 1000 / 60 % 60);
    var s = Math.floor(t / 1000 % 60);
    if (d.toString().length <= 1) {
      d = "0" + d;
    }
    if (h.toString().length <= 1) {
      h = "0" + h;
    }
    if (m.toString().length <= 1) {
      m = "0" + m;
    }
    if (s.toString().length <= 1) {
      s = "0" + s;
    }
    return d + "," + h + "," + m + "," + s;
  } else {
    return "";
  }
}

//日期转换,兼容苹果安卓
function newDate(strdate) {
  var arr = strdate.split(/[- : \/]/);
  var date = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
  return date;
}